using System;
using System.ComponentModel;

namespace PrismFactory.SoftwareFactory.Views
{
    public abstract class ViewModelBase : INotifyPropertyChanged, IDataErrorInfo
    {
        protected static string[] ValidatedProperties = new string[0];

        public event PropertyChangedEventHandler PropertyChanged;

        public bool IsValid
        {
            get
            {
                foreach (string property in ValidatedProperties)
                {
                    if (GetValidationError(property) != null)
                    {
                        return false;
                    }
                }
                string error = "";
                return DoGlobalValidation(ref error);
            }
        }

        public string this[string columnName]
        {
            get { return GetValidationError(columnName); }
        }

        public string Error
        {
            get { return null; }
        }

        protected void OnPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        protected string GetValidationError(string propertyName)
        {
            if (Array.IndexOf(ValidatedProperties, propertyName) < 0)
                return null;

            string error = null;
            DoPropertyValidation(propertyName, ref error);
            return error;

        }

        protected abstract void DoPropertyValidation(string propertyName, ref string error);
        protected virtual bool DoGlobalValidation(ref string error)
        {
            return true;
        }
    }
}